<?php

namespace app\api\model;

use think\Model;

class Theme extends BaseModel
{

    protected $hidden = [ 'delete_time', 'update_time' ];

    public function topicImg()
    {
        return $this->belongsTo('Image', 'topic_img_id', 'id');
    }

    public function headImg()
    {
        return $this->belongsTo('Image', 'head_img_id', 'id');
    }

    public function products()
    {
        return $this->belongsToMany('Product', 'theme_product', 'product_id', 'theme_id');
    }

    public static function getThemeWithProducts($id)
    {
        $themes = self::with('products,topicImg,headImg')
                ->find($id);
        return $themes;
    }

    public static function addThemeProduct($themeID, $productID)
    {
        $theme_model = self::checkRelationExist($themeID, $productID);
//     先检测存在,再添加数据
        $theme_model->products()->attach($productID);
    }

    public static function deleteThemeProduct($themeID, $productID)
    {
        $theme_model = self::checkRelationExist($themeID, $productID);
//     先检测存在,再添加数据
        $theme_model->products()->detach($productID);
    }

    /**
     * 添加主题和商品关联表前,先检测数据是否存在
     * @param type $themeID
     * @param type $productID
     * @return type $theme_model
     * @throws \app\api\exception\ProductException
     * @throws \app\api\exception\ThemeException
     */
    private static function checkRelationExist($themeID, $productID)
    {
        $product_model = Product::get($productID);
        $theme_model = Theme::get($themeID);
        if (empty($product_model))
        {
            throw new \app\api\exception\ProductException();
        }
        if (empty($theme_model))
        {
            throw new \app\api\exception\ThemeException();
        }
        return $theme_model;
    }

}
